package com.study.Caro;

import java.util.concurrent.locks.ReentrantLock;

import com.study.GameService.NetConnection.GameService;

public class Brain {
	private static Brain instance = null;
	int[][] mPos= null;//new int[12][12];
	public static int TIMEOUT = 20000;
	public static int POINT_BUSY = 0;	// already exist
	public static int POINT_VALID = 1;	// valid to choose
	public static int POINT_WINNING = 2;// winning point
	public static int INVALID_TURN = -1;
	
	private boolean first_player = false;
	private boolean gameToken = false; // false: your friend's turn, true: your turn
	@SuppressWarnings("unused")
	private int time_out = Brain.TIMEOUT;
	
	// Protect token state changed by touch and timeout event 
	private ReentrantLock lockState = null; 
	
	protected Brain(){
		if(mPos == null){
			mPos = new int[Screen.SCREEN_SIZE_Y+1][Screen.SCREEN_SIZE_X+1];
			int i,j;
			for(i=0;i<=Screen.SCREEN_SIZE_Y;i=i+1)
			{	
				for(j=0;j<=Screen.SCREEN_SIZE_X;j=j+1)
				{
					mPos[i][j]=0;
				}			
			}
		}
		if(GameService.GetMode() == GameService.CLIENT_MODE){
			first_player = true;
			gameToken = true;
		}
		if(lockState == null)
			lockState = new ReentrantLock();
	}
	
	public void Reset(){
		if(mPos == null)
			return;
		int i,j;
		for(i=0;i<=Screen.SCREEN_SIZE_Y;i=i+1)
		{	
			for(j=0;j<=Screen.SCREEN_SIZE_X;j=j+1)
			{
				mPos[i][j]=0;
			}			
		}
	}
	
	public static Brain GetInstance(){
		if(instance == null){
			instance = new Brain();
		}
		
		return instance;
	}
	
	public boolean IsMyTurn(){
		return gameToken;
	}
	
	public boolean CheckWin(int posX, int posY){ // the newest choosing point
		boolean ret = false;
		
		return ret;
	}
	
	// Processing all game algorithm here:
	// Check player turn
	// Check win-lost
	// Update game state if valid turn
	public int Processing(int posX, int posY){
		if (getValue(posX, posY) != 0) // invalid point
			return POINT_BUSY;
			// Check turn
		if(IsMyTurn() == false)			// invalid turn
			return INVALID_TURN;

		return POINT_VALID;
	}
	
	// Update value in touched position
	// posX, posY: choosing position
	// myTurn	: true: the player's turn
	//			: false: opposite's turn
	public void UpdateState(int posX, int posY, boolean myTurn){
		gameToken = !gameToken;		

		int option = 1; // associate to X
		if( (myTurn && first_player) || (!myTurn && !first_player) )
				option = 2; // associate to O
			
			setValues(posX, posY, option);		// valid condition --> update position

	}
	
	public void UpdateStateTimeOut(){
		gameToken = !gameToken;
	}
	/*======================================================*/
	
	/*=======================method=========================*/

	public void setValues(int X,int Y,int value) {
		mPos[X][Y] = value;		
	}
	
	public int getValue(int X,int Y) {
		return mPos[X][Y];
	}
	
	public ReentrantLock GetLock(){
		return lockState;
	}
}
